package org.example;

import com.alibaba.excel.EasyExcel;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ExcelUpdater {

    private static final ExecutorService executorService = Executors.newFixedThreadPool(5);  // 控制并发数

    public void updateExcelWithContent(String inputFilePath, String outputFilePath) {
        List<ArticleData> articles = null;
        try {
            // 读取 Excel 文件中的数据
            ExcelReader excelReader = new ExcelReader();
            articles = excelReader.readExcel(inputFilePath);

            // 使用 Jsoup 爬取文章内容
            ArticleContentScraper scraper = new ArticleContentScraper();

            // 创建任务列表
            List<Callable<Void>> tasks = new ArrayList<>();
            for (ArticleData article : articles) {
                tasks.add(() -> {
                    // 获取文章内容并更新
                    String content = scraper.fetchArticleContent(article.getLink());
                    article.setContent(content);  // 设置文章内容
                    return null;
                });
            }

            // 提交任务并获取所有任务的返回结果
            List<Future<Void>> results = executorService.invokeAll(tasks);

            // 等待所有任务完成
            executorService.shutdown();
            while (!executorService.isTerminated()) {
                // 等待所有任务完成
            }

            // 写回更新后的 Excel 文件
            EasyExcel.write(outputFilePath)
                    .head(ArticleData.class)
                    .sheet("Sheet1")
                    .doWrite(articles);  // 写入更新后的数据
            System.out.println("Excel 文件已成功更新！");
        } catch (Exception e) {
            System.err.println("处理过程中发生错误：" + e.getMessage());
        }
    }
}
